package com.nari.ncps.screen.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.mapper.electric.ElectricSafetyenvPlantRtMapper;
import com.nari.ncps.screen.service.electric.ElectricSafetyenvPlantRtService;
import com.nari.ncps.screen.vo.electric.PlantAnnualEmissionStatistics;
import com.nari.ncps.screen.entity.electric.ElectricSafetyenvPlantRt;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 火电安全环保电厂实时数据表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-09-24
 */
@Service
public class ElectricSafetyenvPlantRtServiceImpl extends ServiceImpl<ElectricSafetyenvPlantRtMapper, ElectricSafetyenvPlantRt> implements ElectricSafetyenvPlantRtService {

    @Override
    public List<ElectricSafetyenvPlantRt> getByYear(Integer year) {
        return baseMapper.selectByYear(year);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getByYearAndMonth(Integer year, Integer month) {
        return baseMapper.selectByYearAndMonth(year, month);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getByDate(Integer year, Integer month, Integer day) {
        return baseMapper.selectByDate(year, month, day);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getByPlantCode(String plantCode) {
        return baseMapper.selectByPlantCode(plantCode);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getByCompanyCode(String companyCode) {
        return baseMapper.selectByCompanyCode(companyCode);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getExcessiveEmission(Integer year, Integer month) {
        return baseMapper.selectExcessiveEmission(year, month);
    }

    @Override
    public ElectricSafetyenvPlantRt getMonthlyStatistics(Integer year, Integer month, String plantCode) {
        return baseMapper.selectMonthlyStatistics(year, month, plantCode);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getDailyTrend(Integer year, Integer month, String plantCode) {
        return baseMapper.selectDailyTrend(year, month, plantCode);
    }

    @Override
    public boolean hasExcessiveEmission(Integer year, Integer month) {
        List<ElectricSafetyenvPlantRt> excessiveList = getExcessiveEmission(year, month);
        return excessiveList != null && !excessiveList.isEmpty();
    }

    @Override
    public Double getComplianceRate(Integer year, Integer month, String plantCode) {
        // 查询该电厂当月所有数据
        QueryWrapper<ElectricSafetyenvPlantRt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year)
                   .eq("month", month)
                   .eq("plant_code", plantCode);
        
        List<ElectricSafetyenvPlantRt> allData = list(queryWrapper);
        
        if (allData == null || allData.isEmpty()) {
            return 100.0; // 无数据时返回100%
        }
        
        // 统计达标的数据条数
        long compliantCount = allData.stream()
            .filter(data -> isCompliant(data))
            .count();
        
        // 计算达标率
        double rate = (double) compliantCount / allData.size() * 100;
        return BigDecimal.valueOf(rate)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }

    @Override
    public ElectricSafetyenvPlantRt getLatestDataByPlant(String plantCode) {
        QueryWrapper<ElectricSafetyenvPlantRt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plant_code", plantCode)
                   .orderByDesc("year", "month", "day", "create_time")
                   .last("LIMIT 1");
        
        return getOne(queryWrapper);
    }

    @Override
    public List<ElectricSafetyenvPlantRt> getLatestDataByCompany(String companyCode) {
        // 查询该公司下所有电厂的最新数据
        QueryWrapper<ElectricSafetyenvPlantRt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_code", companyCode);
        
        List<ElectricSafetyenvPlantRt> allData = list(queryWrapper);
        
        if (allData == null || allData.isEmpty()) {
            return allData;
        }
        
        // 按电厂分组，取每个电厂的最新数据
        Map<String, ElectricSafetyenvPlantRt> latestDataMap = allData.stream()
            .collect(Collectors.groupingBy(
                ElectricSafetyenvPlantRt::getPlantCode,
                Collectors.maxBy((a, b) -> {
                    // 按年、月、日、创建时间排序
                    int yearCompare = Integer.compare(a.getYear(), b.getYear());
                    if (yearCompare != 0) return yearCompare;
                    
                    int monthCompare = Integer.compare(a.getMonth(), b.getMonth());
                    if (monthCompare != 0) return monthCompare;
                    
                    int dayCompare = Integer.compare(a.getDay(), b.getDay());
                    if (dayCompare != 0) return dayCompare;
                    
                    if (a.getCreateTime() != null && b.getCreateTime() != null) {
                        return a.getCreateTime().compareTo(b.getCreateTime());
                    }
                    
                    return 0;
                })
            ))
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue().isPresent())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().get()
            ));
        
        return latestDataMap.values().stream().collect(Collectors.toList());
    }

    /**
     * 判断排放数据是否达标
     * @param data 排放数据
     * @return 是否达标
     */
    private boolean isCompliant(ElectricSafetyenvPlantRt data) {
        // 检查粉尘排放是否达标
        if (data.getDustAmount() != null && data.getDustStandard() != null) {
            if (data.getDustAmount() > data.getDustStandard()) {
                return false;
            }
        }
        
        // 检查硫化物排放是否达标
        if (data.getSulfurAmount() != null && data.getSulfurStandard() != null) {
            if (data.getSulfurAmount() > data.getSulfurStandard()) {
                return false;
            }
        }
        
        // 检查氮氧化物排放是否达标
        if (data.getNitrogenAmount() != null && data.getNitrogenStandard() != null) {
            if (data.getNitrogenAmount() > data.getNitrogenStandard()) {
                return false;
            }
        }
        
        return true;
    }

    @Override
    public List<PlantAnnualEmissionStatistics> getPlantAnnualEmissionStatistics(Integer year) {
        // 如果year为空，使用当前年份
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        
        // 查询指定年份的所有数据
        QueryWrapper<ElectricSafetyenvPlantRt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year);
        List<ElectricSafetyenvPlantRt> dataList = this.list(queryWrapper);
        
        if (dataList == null || dataList.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        
        // 按电厂分组统计
        Map<String, List<ElectricSafetyenvPlantRt>> groupedByPlant = dataList.stream()
                .collect(Collectors.groupingBy(ElectricSafetyenvPlantRt::getPlantCode));
        
        // 转换为统计结果
        List<PlantAnnualEmissionStatistics> result = new java.util.ArrayList<>();
        for (Map.Entry<String, List<ElectricSafetyenvPlantRt>> entry : groupedByPlant.entrySet()) {
            List<ElectricSafetyenvPlantRt> plantData = entry.getValue();
            PlantAnnualEmissionStatistics statistics = calculatePlantStatistics(year, plantData);
            result.add(statistics);
        }
        
        // 按电厂编码排序
        result.sort((a, b) -> a.getPlantCode().compareTo(b.getPlantCode()));
        
        return result;
    }
    
    /**
     * 计算单个电厂的年度统计数据
     */
    private PlantAnnualEmissionStatistics calculatePlantStatistics(Integer year, List<ElectricSafetyenvPlantRt> plantData) {
        if (plantData == null || plantData.isEmpty()) {
            return new PlantAnnualEmissionStatistics();
        }
        
        PlantAnnualEmissionStatistics statistics = new PlantAnnualEmissionStatistics();
        
        // 基本信息（取第一条记录）
        ElectricSafetyenvPlantRt first = plantData.get(0);
        statistics.setYear(year);
        statistics.setCompanyCode(first.getCompanyCode());
        statistics.setCompanyName(first.getCompanyName());
        statistics.setPlantCode(first.getPlantCode());
        statistics.setPlantName(first.getPlantName());
        
        // 统计机组数量（去重）
        long unitCount = plantData.stream()
                .map(ElectricSafetyenvPlantRt::getUnitCode)
                .filter(UnitCode -> UnitCode != null && !UnitCode.isEmpty())
                .distinct()
                .count();
        statistics.setUnitCount((int) unitCount);
        
        // 累计排放量
        long totalDust = plantData.stream()
                .mapToLong(item -> item.getDustAmount() != null ? item.getDustAmount() : 0)
                .sum();
        long totalSulfur = plantData.stream()
                .mapToLong(item -> item.getSulfurAmount() != null ? item.getSulfurAmount() : 0)
                .sum();
        long totalNitrogen = plantData.stream()
                .mapToLong(item -> item.getNitrogenAmount() != null ? item.getNitrogenAmount() : 0)
                .sum();
        
        statistics.setTotalDustAmount(totalDust);
        statistics.setTotalSulfurAmount(totalSulfur);
        statistics.setTotalNitrogenAmount(totalNitrogen);
        
        // 排放标准（取最新的标准值）
        ElectricSafetyenvPlantRt latest = plantData.stream()
                .max((a, b) -> {
                    int monthCompare = Integer.compare(
                            a.getMonth() != null ? a.getMonth() : 0,
                            b.getMonth() != null ? b.getMonth() : 0
                    );
                    if (monthCompare != 0) return monthCompare;
                    return Integer.compare(
                            a.getDay() != null ? a.getDay() : 0,
                            b.getDay() != null ? b.getDay() : 0
                    );
                })
                .orElse(first);
        
        statistics.setDustStandard(latest.getDustStandard());
        statistics.setSulfurStandard(latest.getSulfurStandard());
        statistics.setNitrogenStandard(latest.getNitrogenStandard());
        
        // 计算达标率
        long compliantCount = plantData.stream()
                .filter(this::isCompliant)
                .count();
        double overallRate = plantData.size() > 0 ? 
                (double) compliantCount / plantData.size() * 100 : 100.0;
        statistics.setOverallComplianceRate(
                BigDecimal.valueOf(overallRate).setScale(2, RoundingMode.HALF_UP).doubleValue()
        );
        
        // 单项达标率（简化计算）
        statistics.setDustComplianceRate(statistics.getOverallComplianceRate());
        statistics.setSulfurComplianceRate(statistics.getOverallComplianceRate());
        statistics.setNitrogenComplianceRate(statistics.getOverallComplianceRate());
        
        // 运行状态（根据达标率判断）
        statistics.setStatus(statistics.getOverallComplianceRate() >= 95.0 ? 0 : 1);
        
        // 记录数
        statistics.setRecordCount(plantData.size());
        
        return statistics;
    }

}
